class Goods {
    static goodsArr = [];
    constructor(index, item) {
        this.index = index;
        this.id = item.id;
        this.gid = item.gid;
        this.num = +item.num;
        this.name = item.name;
        this.price = +item.price;
        this.title = item.title;
        this.cover = item.cover;
        Goods.goodsArr.push(this);
    }
    get total() {
        return this.num * this.price;
    }
    
    del() {
        $.ajax({
            type: "post",
            url: "/delCart",
            data: {
                id: this.id,
            },
        }).done((res) => {
            console.log(res);
        })
    }
    update(num=this.num) {
        $.ajax({
            type: "post",
            url: "/updateCart",
            data: {
                num: num,
                id: this.id,
            },
        }).done((res) => {
            console.log(res);
        })
    }
    reduce() {
        if (this.num - 1 <= 0) {
            return;
        }
        --this.num;
        this.update();
    }
    add() {
        ++this.num;
        this.update()
    }
    static locale(price) {
        return price.toLocaleString('en-US', {
            minimumFractionDigits: 2
        })
    }
    static countAllTotal() {
        return Goods.goodsArr.reduce((res, item) => {
            return res + item.total;
        }, 0);
    }
    static insert({
        uid,
        gid,
        addNum
    }) {
        let goods = Goods.goodsArr.find(item => {
            return item.gid == gid;
        })
        console.log(goods);
        if (goods) {
            if (addNum) {
                goods.update(goods.num+=addNum);
            } else {
                goods.add();
            }
        } else {
            $.ajax({
                type: "post",
                url: "/insertCart",
                data: {
                    uid,
                    gid,
										num: addNum ? addNum : 1
                },
            }).done((res) => {
                console.log(res);
            })
        }
    }
    static remove(index) {
        let i = Goods.findIndex(index);
        Goods.goodsArr[i].del();
        Goods.goodsArr.splice(i, 1);
    }
    static findIndex(index) {
        return Goods.goodsArr.findIndex((item) => {
            return item.index == index;
        })
    }
    static find(index) {
        return Goods.goodsArr.find((item) => {
            return item.index == index;
        })
    }
}